package net.xinqushi.action;
import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionContext;

import net.xinqushi.model.User;
import net.xinqushi.service.UserService;
public class UserAction{
	private User user;
	UserService service;
	public UserService getService() {
		return service;
	}
	@Resource(name="service")
	public void setService(UserService service) {
		this.service = service;
	}

	public User getUser() {
		return user;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	
	public String add()
	{
		service.add(user);
		//将当前登录用户的信息保存起来
		ActionContext.getContext().getSession().put("USER", user);
		return "main";
	}
	public String checkExists() throws IOException
	{
		boolean flag=service.checkExists(user);
		HttpServletResponse response= ServletActionContext.getResponse();
		PrintWriter out =response.getWriter();
		if(flag)
		{
			out.print("1");
		}
		else
		{
			out.print("0");
		}
		return null;
	}
	public String logout()
	{
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session =request.getSession();
		//session 失效
		session.setAttribute("USER", null);
		return "main";
	}
	
	public String login()
	{
		HttpServletRequest request=ServletActionContext.getRequest();
		HttpSession session =request.getSession();
		String result="login";
		if(service.checkExists(user))
		{
			session.setAttribute("USER", user);
			result="main";
		}
		return result;
		
	}
}
